package com.aruba.mvvmapplication.repository

import androidx.paging.*
import com.aruba.mvvmapplication.database.AppDatabase
import com.aruba.mvvmapplication.di.RetrofitModule
import com.aruba.mvvmapplication.mapper.MovieEntity2ItemModelMapper
import com.aruba.mvvmapplication.model.MovieItemModel
import com.aruba.mvvmapplication.remote.MovieRemoteMediator
import com.aruba.mvvmapplication.remote.MovieService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map

/**
 * Created by aruba on 2021/9/24.
 */
class MovieRepositoryImpl(
    private val api: MovieService,
    private val appDatabase: AppDatabase,
    private val mapper: MovieEntity2ItemModelMapper
) : Repository<MovieItemModel> {

    @OptIn(ExperimentalPagingApi::class)
    override fun fetchList(): Flow<PagingData<MovieItemModel>> {
        val pageSize = 10
        
        return Pager(
            config = PagingConfig(
                initialLoadSize = pageSize * 2,
                pageSize = pageSize,
                prefetchDistance = 1
            ),
            remoteMediator = MovieRemoteMediator(api, appDatabase)
        ) {
            appDatabase.movieDao().getMovieList()
        }.flow.flowOn(Dispatchers.IO).map { pagingData ->
            pagingData.map { mapper.map(it) }
        }
    }

}